package com.parkreport.sysinit;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletConfig;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;


public class SysInitService {


	/**
     * 初始化应用程序的各种码表或选项值
     * @param config
     */
	public static void initSysOptions(ServletConfig config){
    	try {
			loadSysOptions(config,new FileInputStream(config.getServletContext().getRealPath("/WEB-INF/system.xml")));
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
	/**
	 * 为每个应用模块加载其各种码表或系统选项。
	 * @param is
	 * @throws Exception
	 */
    private static void loadSysOptions(ServletConfig config,InputStream is) throws Exception{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(is);
		is.close();
		
		List<Node> paramList = doc.selectNodes("//system-params/param");
		if(paramList != null && paramList.size() > 0){
			for(Node n : paramList){
				List<Node> data = n.selectNodes("./data");
				Map<String,String> dataMap = new TreeMap<String,String>();
				if(data.size() > 0){
					for(Node b : data){
						dataMap.put(b.valueOf("@key"),b.getText());
						//AppMap.SYSMAP.put(b.valueOf("@key"),b.getText());
					}
				}
				String beanName = n.valueOf("@appBeanName");
				if(beanName != null && !"".equals(beanName)){
					config.getServletContext().setAttribute(beanName, dataMap);
					
				}
				
			}
		}
    }
}
